package com.example.myapp61;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.icu.text.DateFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

import com.ejlchina.okhttps.HttpResult;
import com.example.myapp61.Mfragment.MFragmentAdapter;
import com.example.myapp61.Mfragment.fragment1;
import com.example.myapp61.Mfragment.fragment2;
import com.example.myapp61.Mfragment.fragment3;
import com.example.myapp61.Util.AppUtil;
import com.example.myapp61.Util.HttpUtil;
import com.example.myapp61.Util.ToasUtil;
import com.google.gson.Gson;
import com.xuexiang.xutil.data.DateUtils;
import com.xuexiang.xutil.data.SPUtils;
import com.xuexiang.xutil.display.BarUtils;
import com.xuexiang.xutil.system.DeviceUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "测试";
    private ViewPager viewPager;
    private List<Fragment> list;
    private ArrayList<String> title;
    private MFragmentAdapter mFragmentAdapter;
    //更新相关参数
    protected ProgressDialog pro1;
    protected int pross =0;
    private final int MAX_PROSS =100;
    private static AlertDialog alert;
    private static AlertDialog.Builder builder;
    private File SDpaths;

    private Context context = this;


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化工作
        initView();
        //检查更新
        updata();
        //获取手机信息

        if (!SPUtils.contains(SPUtils.getSharedPreferences("androidId"), "id")) { getandroidId(); }
    }

    //上传手机信息
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void getandroidId() {
        SimpleDateFormat formatter    =   new    SimpleDateFormat    ("yyyy年MM月dd日 HH:mm:ss");
        Date curDate    =   new    Date(System.currentTimeMillis());//获取当前时间
        String androidId =  DeviceUtils.getAndroidID(); //手机Id
        String androidBrand =  DeviceUtils.getDeviceBrand(); //手机品牌
        String    str    =    formatter.format(curDate); //时间
        Map<String, String> data = new HashMap<>();
        data.put("androidId",androidId);
        data.put("androidBrand",androidBrand);
        data.put("time",str);
        String res =  HttpUtil.http.async("/androidId")
                .addBodyPara(data)
                .post().getResult().getBody().toString();
        if (res.equals("1")){ SPUtils.putBoolean(SPUtils.getSharedPreferences("androidId"),"id",true); }
    }

    /**
     * APP初始化工作
     */
    private void initView() {
        viewPager = findViewById(R.id.IdPager);
        viewPager.addOnPageChangeListener(new MyPagerChangeListener());
        list = new ArrayList<>();
        title = new ArrayList<>();
        //fragment页面的增加
        list.add(new fragment2());
        list.add(new fragment1());
        list.add(new fragment3());
        //fragment的标题的增加
        title.add("增加");
        title.add("首页");
        title.add("我的");

        mFragmentAdapter = new MFragmentAdapter(getSupportFragmentManager(),list,title);
        viewPager.setAdapter(mFragmentAdapter);
        //设置默认页面
        viewPager.setCurrentItem(1);
        //设置状态栏透明度
        //BarUtils.setStatusBarAlpha(MainActivity.this,50);

        /**
         * 获取外部SD卡路径
         */
        SDpaths =  Environment.getExternalStorageDirectory();
        Log.d(TAG, "run: "+SDpaths);
    }

    @Override
    public void onClick(View view) {
    }
    private class MyPagerChangeListener implements ViewPager.OnPageChangeListener {
        /**
         * 当页面在滑动的时候会调用此方法
         * @param position 当前页面
         * @param positionOffset 当前页面偏移的百分比
         * @param positionOffsetPixels 当前页面偏移的像素位置
         */
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        /**
         * 此方法是页面跳转完后得到调用
         *          position:是你当前选中的页面的Position
         * @param position
         */
        @Override
        public void onPageSelected(int position) {

        }

        /**
         * 此方法是在状态改变的时候调用，其中state这个参数有三种状态：
         *          1.按在屏幕上并且开始拖动
         *          2.手指离开屏幕
         *          0.滑动动画做完的状态
         * @param state
         */
        @Override
        public void onPageScrollStateChanged(int state) {
        }
    }

    /**
     * 更新相关
     */

    private void updata() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    StringBuilder b = HttpUtil.updata("https://yeqt.top:3005/updata");
                    Gson g = new Gson();
                    Updata up = g.fromJson(b.toString(),Updata.class);
                    double ver = Double.parseDouble(AppUtil.getVersionName(MainActivity.this));//字符串转换为数值型
                    //Log.d(TAG, "run: "+ver+"远程版本："+up.version);
                    if (ver == up.version){
                        Log.d(TAG, "run: "+"版本相同");
                    }else{
                        Log.d(TAG, "run: "+"版本不同");
                    }
                    if (up.version>ver){
                        Message message = new Message();
                        message.what=1;
                        message.obj=up.content;
                        handler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    public Thread T1 = new Thread(new Runnable() {
        @Override
        public void run() {
            URL url = null;
            HttpURLConnection getconn = null;
            try {
                url = new URL("https://yeqt.top:3005/public/Android_ssbbm.apk");
                getconn = (HttpURLConnection) url.openConnection();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            BufferedInputStream bis =null;
            BufferedOutputStream bos=null;
            long len = 0;
            try {
                len = getconn.getContentLength();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (len>32){
                try {
                    InputStream is = getconn.getInputStream();
                    bis = new BufferedInputStream(is);
                    FileOutputStream fos = new FileOutputStream(SDpaths+"/Download/Android_ssbbm.apk");
                    bos = new BufferedOutputStream(fos);
                    int b = 0;
                    long ii =0;
                    byte[] byArr = new byte[1024];
                    while((b= bis.read(byArr))!=-1){
                        bos.write(byArr, 0, b);
                        ii+=b;
                        //进度条算法
                        pross = (int) (ii*100/len);
                        handler.sendEmptyMessage(2);
                    }
                    bis.close();
                    bos.close();
                    getconn.disconnect();
                    handler.sendEmptyMessage(3);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });
    /**
     * handler，更新主线程UI
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what ==1){
                //联网判定是否有更新
                UpdataAlert(msg.obj.toString());
            }
            if (msg.what==2){
                //下载进度更新
                pro1.setProgress(pross);
            }
            if (msg.what==3){
                //下载完成后执行安装
                startInstall(SDpaths+"/Download/Android_ssbbm.apk");
            }
            if (pross>=MAX_PROSS){pro1.dismiss();}
        }
    };

    /**
     * 弹出更新的通知
     * @param msg  更新的信息
     */
    private void UpdataAlert(String msg) {
        requestPermission();
        alert = null;
        builder = new AlertDialog.Builder(context);
        alert = builder.setTitle("有更新啦")
                .setMessage(msg)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ToasUtil.showMes(context,"点击了取消");
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        pro1 = new ProgressDialog(MainActivity.this);
                        pro1.setTitle("下载中");
                        pro1.setMessage("软件更新中》》》");
                        pro1.setCancelable(true);
                        pro1.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        pro1.setIndeterminate(false);
                        pro1.show();
                        T1.start();
                    }
                }).create();
        alert.show();
    }
    /**
     * 权限获取
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ //同意权限申请
                }else { //拒绝权限申请
                    ToasUtil.showMes(this,"权限被拒绝了");
                }
                break;
            default:
                break;
        }
    }

    private void requestPermission(){
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ //表示未授权时
            //进行授权
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }else{
            ToasUtil.showMes(this,"用户已授权！");
        }
    }


    /**
     * 此方法网上copy的，作用是安装包下载完后自动打开
     * @param filePath
     */
    private void startInstall(String filePath){
        //分别进行7.0以上和7.0以下的尝试
        File apkfile = new File(filePath);
        if (!apkfile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //7.0以上
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(getApplicationContext(),"com.example.myapp61.fileProvider",apkfile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        }else{
            intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

}